package com.cb.controller.front.system;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import com.cb.common.util.ConfigUtil;
import com.cb.common.webapp.context.RequestContext;
import com.cb.core.command.QueryFilter;
import com.cb.core.command.QueryResult;
import com.cb.core.controller.BaseListController;
import com.cb.domain.model.order.BOrder;
import com.cb.domain.model.order.PassengerDto;
import com.cb.domain.model.system.City;
import com.cb.domain.model.system.Media;
import com.cb.domain.model.system.SystemHelp;
import com.cb.domain.model.user.UserAccount;
import com.cb.domain.service.order.BOrderManager;
import com.cb.domain.service.order.OrderLogManager;
import com.cb.domain.service.system.CityManager;
import com.cb.domain.service.system.MediaManager;
import com.cb.domain.service.system.SystemHelpManager;

/**
 * 
 * @Author author
 * @Vesion 1.0 Create Time:
 *         <p>
 *         <b>Class Description:</b>[TODO]
 *         <p>
 */

public class IndexController extends BaseListController {

	@Autowired
	private SystemHelpManager systemHelpManager;
	
	@Autowired
	private MediaManager mediaManager;
	
	@Autowired
	private BOrderManager bOrderManager;
	
	@Autowired
	private OrderLogManager orderLogManager;
	
	@Autowired
	private CityManager cityManager;
	
	protected Map<String,String> successPage;
	
	public void setSuccessPage(Map<String, String> successPage) {
		this.successPage = successPage;
	}

	protected Map<String,String> actionType;
	
	public void setActionType(Map<String, String> actionType) {
		this.actionType = actionType;
	}
	
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
			List<SystemHelp> systemHelps=systemHelpManager.getAll();
			ModelMap modelMap=new ModelMap();
			modelMap.addAttribute("systemHelps", systemHelps);
			
			List<Media> medias=mediaManager.getAll();
			modelMap.addAttribute("medias", medias);
			
	     return new ModelAndView("/front/index",modelMap);
	}
	
	/**
	 * 未登录查询订单
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView logoutOrders(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		QueryFilter filter=new QueryFilter(request);
		HttpSession session=request.getSession();
		String valiCode = request.getParameter("valiCode");
		if(valiCode!=null){
			String vcode = session.getAttribute("vcode").toString();
			if(!valiCode.toUpperCase().equals(vcode.toUpperCase())){
				request.getSession().setAttribute("msg", "验证码错误!");
				return new ModelAndView("front/order/searchOrder");
			} else{
				request.getSession().removeAttribute("msg");
			}
		}

		QueryResult queryResult=bOrderManager.getAll(filter);
		
		return new ModelAndView("front/order/orderList","bOrders",queryResult);
	}
	
	
	/**
	 * 查看实体对象详细信息
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView viewDetail(HttpServletRequest request,	HttpServletResponse response){
		String id=request.getParameter("id");
		BOrder bOrder=null;
		ModelMap modelMap=new ModelMap();
		if(StringUtils.isNotEmpty(id)){
			bOrder=bOrderManager.get(new Long(id));
			List<PassengerDto> passengerDtos= bOrderManager.passenger2dto(bOrder.getPassengers());
			modelMap.addAttribute("passengerDtos", passengerDtos);
			UserAccount account=RequestContext.getCurrentUser();
			if(account!=null){
				String action="查看订单"+bOrder.getOrderNo();
				orderLogManager.saveLog(action, "1",bOrder.getId().toString());
			}
		}
		modelMap.addAttribute("bOrder", bOrder);
		return new ModelAndView("front/order/orderDetail").addAllObjects(modelMap);
	}
	
	
	/**
	 * 跳转订单修改页面
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView toUpdate(HttpServletRequest request,	HttpServletResponse response){
		String id=request.getParameter("id");
		String type=request.getParameter("actionType");
		
		String page="";
		ModelMap map=new ModelMap();
		if(StringUtils.isNotEmpty(id)&&StringUtils.isNotEmpty(type)){
			BOrder bOrder=bOrderManager.get(new Long(id));
			map.addAttribute("bOrder",bOrder);
			List<PassengerDto> passengerDtos= bOrderManager.passenger2dto(bOrder.getPassengers());
			map.addAttribute("passengerDtos", passengerDtos);
			map.addAttribute("actionType", type);

			 page=actionType.get(type);
		}
		
		return new ModelAndView(page).addAllObjects(map);
	}
	
	/**
	 * 执行订单修改
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView doUpdate(HttpServletRequest request,	HttpServletResponse response){
		String id=request.getParameter("id");
		String type=request.getParameter("actionType");

		String description=request.getParameter("description");
		String msg="";
		ModelMap map=new ModelMap();
		if(StringUtils.isNotEmpty(id)&&StringUtils.isNotEmpty(type)){
			BOrder bOrder=bOrderManager.get(new Long(id));
			//改签
			if(type.equals("40")){
				bOrder.setChangeDescription(description);
				msg="你的改签申请已成功提交,请您在发送申请以后拨打我们的客服热线，与客服确认相关事宜。";
			}else if(type.equals("8")){//退票
				bOrder.setReturnDescription(description);
				msg="你的退票已成功提交,请您在发送申请以后拨打我们的客服热线，与客服确认相关事宜。";
			}
			String passengerIds []=request.getParameterValues("passengerIds");
			if(passengerIds.length==bOrder.getPassengers().size()){
					bOrder.setStatus(Long.valueOf(type));
					bOrderManager.save(bOrder);
			}else{
				bOrderManager.newSplitBOrder(bOrder, passengerIds,Long.valueOf(type));
			}
//			page=successPage.get(type);
			String action=getText("bOrder.status"+bOrder.getStatus())+"修改为"+getText("bOrder.status"+type)+bOrder.getOrderNo();
			orderLogManager.saveLog(action, "1",bOrder.getId().toString());
		}
		
		QueryFilter filter=new QueryFilter(request);
		filter.addFilter("Q_id_L_EQ", id);
		QueryResult queryResult=bOrderManager.getAll(filter);
		
		return new ModelAndView("front/order/orderList","bOrders",queryResult).addObject("msg", msg);
		
	}
	
	/**
	 * 取消订单
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView cancelOrder(HttpServletRequest request,	HttpServletResponse response){
		String id=request.getParameter("id");
		BOrder bOrder=null;
		if(StringUtils.isNotEmpty(id)){
			bOrder=bOrderManager.get(new Long(id));
			bOrder.setStatus(new Long(12));
			
			
			String user = ConfigUtil.getInstance().getProperty("abe.userId");
			String password = ConfigUtil.getInstance().getProperty("abe.password");
			String server = ConfigUtil.getInstance().getProperty("abe.server");
			String port = ConfigUtil.getInstance().getProperty("abe.port");
			String maxPage = ConfigUtil.getInstance().getProperty("abe.maxPage");

			String identity = getText("abe.identity", new Object[] { user,
					password, server, port, maxPage });
			Boolean flag=true;
			if(bOrder.getStatus()==0){
				flag=bOrderManager.xePnr(bOrder.getPnr(), identity);
			}
			if(flag){
				bOrderManager.save(bOrder);
				String action="取消订单"+bOrder.getOrderNo();
				orderLogManager.saveLog(action, "1",bOrder.getId().toString());
			}
		}
		return new ModelAndView("redirect:front/index.do?cmd=viewDetail&id="+bOrder.getId());
	}
	
	
	/**
	 * 帮助详细页
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView helpDetail(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		
		List<SystemHelp> systemHelps=systemHelpManager.getAll();
		ModelMap modelMap=new ModelMap();
		
		String helpId=request.getParameter("id");
		SystemHelp systemHelp=new SystemHelp();
		if(StringUtils.isNotBlank(helpId)){
			systemHelp=systemHelpManager.get(Long.valueOf(helpId));
		}
	
		request.setAttribute("systemHelps", systemHelps);
		modelMap.addAttribute("systemHelp", systemHelp);
			
	    return new ModelAndView("/front/system/domesticHelp",modelMap);
	}
	
	public void initCity(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		QueryFilter filter=new QueryFilter();
		filter.addFilter("Q_naCd_S_EQ", "CN");
		List<City> cities=cityManager.getAllList(filter);
	
		JSONArray jsonArray=new JSONArray();
		
		for (City city : cities) {
			   
		     try {
		    	JSONObject jo = new JSONObject(); 
				jo.put("name", city.getCtCn());
				jo.put("code", city.getAptCode());
				jo.put("eName", city.getCtEn());
				jsonArray.put(jo);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		response.getWriter().print(jsonArray.toString());
		
	}
	
}
